using Android.Content;
using Android.Database;
using CapstoneProject.Models;
using System.Collections.Generic;

namespace CapstoneProject.DataAccess
{
    public class StandardAccountRepository : IAccountRepository
    {
        private AccountDatabaseHelper helper;

        public StandardAccountRepository(Context context)
        {
            helper = new AccountDatabaseHelper(context);
        }

        public IList<Account> GetAllAccounts()
        {
            ICursor accountCursor = 
                helper.ReadableDatabase.Query("Account", null, null, null, null, null, null);
            var accounts = new List<Account>();

            while (accountCursor.MoveToNext())
            {
                accounts.Add(mapAccount(accountCursor));
            }
            return accounts;
        }

        public long AddAccount(string username, string password, string fiUrl, string fiOrg, string fid, string accountId, string bankId, string accountName, int userId)
        {
            var values = new ContentValues();
            values.Put("Username", username);
            values.Put("Password", password);
            values.Put("FiUrl", fiUrl);
            values.Put("FiOrg", fiOrg);
            values.Put("Fid", fid);
            values.Put("BankAccountId", accountId);
            values.Put("BankId", bankId);
            values.Put("AccountName", accountName);
            values.Put("UserId", userId);
            values.Put("Balance", 00.00);

            return helper.WritableDatabase.Insert("Account", null, values);
        }

        public void UpdateAccount(int accountId, double balance)
        {
            var values = new ContentValues();
            values.Put("Balance", balance);
            string[] id = new string[1];
            id[0] = accountId.ToString();
            helper.WritableDatabase.Update("Account", values, "AccountId=?", id);
        }

        public void DeleteAccount(int accountId)
        {
            string[] id = new string[1];
            id[0] = accountId.ToString();

            helper.WritableDatabase.Delete("Account", "AccountId=?", id);
        }

        private Account mapAccount(ICursor cursor)
        {
            return new Account
            {
                AccountId = cursor.GetInt(0),
                Username = cursor.GetString(1),
                Password = cursor.GetString(2),
                FiUrl = cursor.GetString(3),
                FiOrg = cursor.GetString(4),
                Fid = cursor.GetString(5),
                BankAccountId = cursor.GetString(6),
                BankId = cursor.GetString(7),
                AccountName = cursor.GetString(8),
                UserId = cursor.GetInt(9),
                Balance = cursor.GetInt(10)
            };
        }
    }
}